package com.asianrapid.core.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Auther: 迟家鑫
 * @Date: 2018/6/19 13:42
 * @Description: 提供能够加载资源文件的实用程序类。
 */
public final class ResourceUtils {

	/**
	 * 构造函数。
	 */
	private ResourceUtils() {
	}

	/** Logger **/
	private static Logger logger = LoggerFactory.getLogger(ResourceUtils.class);

	/**
	 * 使用加载的资源文件进行{@link Properties}转换的方法。
	 *
	 * @param resourcePath 资源文件的绝对路径
	 * @return 资源文件加载的{@link Properties}对象
	 */
	public static Properties reloadProperties(String resourcePath) {
		Properties properties = new Properties();
		FileInputStream fs = null;
		try {
			File file = new File(resourcePath);
			fs = new FileInputStream(file);
			properties.load(fs);

		} catch (FileNotFoundException e) {
			File file = new File(resourcePath);
			File alt = new File(resourcePath + ".zh");
			if (alt.exists()) {
				try {
					BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(alt), "UTF-8"));
					BufferedWriter writer = new BufferedWriter(new FileWriter(file));
					String line = null;
					while ((line = reader.readLine()) != null) {
						String trimed = line.trim();
						if (!trimed.startsWith("#") && !trimed.startsWith("!")) {
							/* native2ascii */
							line = StringUtils.native2Ascii(line);
						}
						writer.write(line);
						writer.newLine();
					}
					reader.close();
					writer.close();
					fs = new FileInputStream(file);
					properties.load(fs);

				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error("reloadProperties(String)", e);

		} finally {
			if (fs != null) {
				try {
					fs.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return properties;
	}

}
